package com.Endurancer.manager.service.impl;

import java.util.List;

import com.Endurancer.common.constant.Constants;
import com.Endurancer.common.constant.UserConstants;
import com.Endurancer.common.core.domain.AjaxResult;
import com.Endurancer.common.core.domain.entity.SysUser;
import com.Endurancer.common.utils.DateUtils;
import com.Endurancer.common.utils.MessageUtils;
import com.Endurancer.common.utils.SecurityUtils;
import com.Endurancer.framework.manager.AsyncManager;
import com.Endurancer.framework.manager.factory.AsyncFactory;
import com.Endurancer.manager.domain.SysUserRole;
import com.Endurancer.manager.domain.dto.UserDto;
import com.Endurancer.manager.domain.vo.UserVo;
import com.Endurancer.manager.mapper.SysUserMapper;
import com.Endurancer.manager.mapper.SysUserRoleMapper;
import com.Endurancer.manager.service.ISysUserService;
import com.Endurancer.manager.utils.NickNameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.Endurancer.manager.mapper.UserMapper;
import com.Endurancer.manager.domain.User;
import com.Endurancer.manager.service.IUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户信息Service业务层处理
 *
 * @author Endurancer
 * @date 2025-02-02
 */
@Service
public class UserServiceImpl implements IUserService
{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper roleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${user.avatar.url}")
    private String avatarUrl;
    /**
     * 查询用户信息
     *
     * @param userId 用户信息主键
     * @return 用户信息
     */
    @Override
    public User selectUserByUserId(Long userId)
    {
        return userMapper.selectUserByUserId(userId);
    }

    /**
     * 查询用户信息列表
     *
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        user.setCreateTime(DateUtils.getNowDate());
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserIds(Long[] userIds)
    {
        return userMapper.deleteUserByUserIds(userIds);
    }

    /**
     * 删除用户信息信息
     *
     * @param userId 用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserId(Long userId)
    {
        return userMapper.deleteUserByUserId(userId);
    }

    @Override
    public User selectUserBySysUserId(SysUser sysUser) {
        return userMapper.selectUserBySysUserId(sysUser.getUserId());
    }

    public AjaxResult AppRegister(UserDto userDto) {
        // 参数校验
        AjaxResult validateResult = validateRegisterParams(userDto);
        if (validateResult != null) {
            return validateResult;
        }
        // 检查验证码
        String code = redisTemplate.opsForValue().get(userDto.getPhone());
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("验证码已过期");
        }
        if (!code.equals(userDto.getCode())) {
            return AjaxResult.error("验证码错误");
        }
        return register(userDto);
    }

    @Transactional
    public UserVo getPerson(Long userId) {
        User user = userMapper.selectUserByUserId(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        SysUser sysUser = sysUserMapper.selectUserById(user.getSysUserId());
        userVo.setPhone(sysUser.getUserName());
        userVo.setEmail(sysUser.getEmail());
        return userVo;
    }

    @Transactional
    public int editPerson(UserVo userVo) {
         User user=new User();
         BeanUtils.copyProperties(userVo,user);
         userMapper.updateUser(user);
         User userByUserId = userMapper.selectUserByUserId(userVo.getUserId());
         SysUser sysUser = sysUserMapper.selectUserById(userByUserId.getSysUserId());
         sysUser.setEmail(userVo.getEmail());
         sysUser.setUserName(userVo.getPhone());
         sysUser.setPhonenumber(userVo.getPhone());
         return sysUserMapper.updateUser(sysUser);
    }

    private AjaxResult validateRegisterParams(UserDto userDto) {
        if (StringUtils.isEmpty(userDto.getPhone())) {
            return AjaxResult.error("手机号码不能为空");
        }
        if (StringUtils.isEmpty(userDto.getPassword())) {
            return AjaxResult.error("用户密码不能为空");
        }

        if (userDto.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || userDto.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
            return AjaxResult.error("密码长度必须在5到20个字符之间");
        }
        return null;
    }

    private AjaxResult register(UserDto userDto) {
        // 构建用户信息
        SysUser sysUser = buildSysUser(userDto);
        // 检查用户名唯一性
        if (!sysUserService.checkUserNameUnique(sysUser)) {
            return AjaxResult.error("用户名已存在");
        }
        if (StringUtils.isNotEmpty(userDto.getPhone()) && !sysUserService.checkPhoneUnique(sysUser)) {
            return AjaxResult.error("手机号已绑定其他用户");
        }
        // 注册用户
        boolean regFlag = sysUserService.registerUser(sysUser);
        if (!regFlag) {
            return AjaxResult.error("注册失败");
        }
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(100L);
        roleMapper.insertUserRole(sysUserRole);

        saveUserInfo(sysUser);
        // 记录登录信息
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.REGISTER, MessageUtils.message("user.register.success")));

        // 注册成功，返回SysUser对象
        return AjaxResult.success("注册成功", sysUser);
    }

    private SysUser buildSysUser(UserDto userDto) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userDto.getPhone());
        sysUser.setPhonenumber(userDto.getPhone());
        if (userDto.getPassword()!= null){
            sysUser.setPassword(SecurityUtils.encryptPassword(userDto.getPassword()));
        }
        sysUser.setAvatar(avatarUrl);
//        sysUser.setStatus("0");
        sysUser.setDeptId(201L);
        sysUser.setCreateBy("sys");
        sysUser.setNickName(userDto.getNickname());
        return sysUser;
    }

    private void saveUserInfo(SysUser sysUser) {
        User user = new User();
        user.setAvatar(avatarUrl);
        user.setSysUserId(sysUser.getUserId());
        user.setCreateBy(sysUser.getCreateBy());
        user.setNickName(sysUser.getNickName());
        userMapper.insertUser(user);
    }


}
